/**
 * Copyright (C), 2020, 安徽贝慕信息科技有限公司
 * FileName: BackendApiService
 * Author:   Allen
 * Date:     2020/8/18
 * Description: 开放后端API接口信息
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.bim.marvel.openapi.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.bim.marvel.openapi.client.query.BackendApiQuery;
import com.bim.marvel.openapi.client.query.BackendApiUpdateQuery;
import com.bim.marvel.openapi.core.dao.BackendApiDAO;
import com.bim.marvel.openapi.core.entity.BackendApiDO;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

/**
 * 〈开放后端API接口信息服务类〉
 *
 * @author Allen
 * @date 2020/8/18
 * @since 1.0.0
 */
@Service
public class BackendApiService extends ServiceImpl<BackendApiDAO, BackendApiDO> {

    /**
     * 根据serviceId服务ID和path服务路径查询BackendApiDO，并新增缓存gateway.backendApi
     *
     * @param serviceId 服务ID
     * @param path 服务路径
     * @return BackendApiDO
     */
    @Cacheable(value = "getOpenApiUri", key = "'openApiUrl:' + #serviceId + '_' + #path")
    public Boolean getByServiceIdAndPath(String serviceId, String path) {
        BackendApiDO backendApiDO = new BackendApiDO();
        backendApiDO.setServiceId(serviceId);
        backendApiDO.setPath(path);
        QueryWrapper<BackendApiDO> wrapper = new QueryWrapper<>(backendApiDO);
        return SqlHelper.retBool(count(wrapper));
    }

    /**
     * 更新只能更新名称，其他不能进行更新，故而无须清除缓存
     *
     * @param backendApiQuery 后端接口入参
     * @return 更新结果
     */
// @CacheEvict(value = "getOpenApiUri", key = "'openApiUrl:' + #backendApiQuery.serviceId +'_'+ #backendApiQuery.path")
    public boolean updateBackendApiById(BackendApiUpdateQuery backendApiQuery) {
        BackendApiDO backendApiDO = new BackendApiDO();
        BeanUtils.copyProperties(backendApiQuery, backendApiDO);
        return super.updateById(backendApiDO);
    }

    /**
     * 保存开放API接口地址信息
     * @param backendApiQuery 后端接口实体
     * @return 保存状态
     */
    @Cacheable(value = "getOpenApiUri", key = "'openApiUrl:' + #backendApiQuery.serviceId + '_'+ #backendApiQuery.path")
    public boolean saveBackendApi(BackendApiQuery backendApiQuery) {
        BackendApiDO backendApiDO = new BackendApiDO();
        BeanUtils.copyProperties(backendApiQuery, backendApiDO);
        //对于第三方只能通过签名方式访问，故而此处固定
        backendApiDO.setSignature(true);
        //目前对第三方不开放通过Token访问的方式
        backendApiDO.setToken(false);
        return super.save(backendApiDO);
    }
}
